package com.jiangxfei.mymvp.net;

import android.content.Context;

import com.jiangxfei.mymvp.config.APIUrl;

import io.rx_cache2.internal.RxCache;
import io.victoralbertos.jolyglot.GsonSpeaker;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class RepositoryManager implements IRepositoryManager {

    private Retrofit.Builder rb;
    private OkHttpClient okHttpClient;
    private Context mContext;

    public RepositoryManager(Retrofit.Builder rb, OkHttpClient okHttpClient, Context context) {
        this.rb = rb;
        this.okHttpClient = okHttpClient;
        this.mContext = context;
    }


    @Override
    public <T> T obtainRetrofitService(Class<T> service) {
        return rb.baseUrl(APIUrl.API_URL)
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build().create(service);
    }

    @Override
    public <T> T obtainRetrofitService(Class<T> service, String url) {
        return rb.baseUrl(url)
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build().create(service);
    }

    @Override
    public <T> T obtainCacheService(Class<T> cache) {
        return new RxCache.Builder()
                .persistence(mContext.getCacheDir(), new GsonSpeaker())
                .using(cache);
    }

    @Override
    public void clearAllCache() {

    }

    @Override
    public Context getContext() {
        return mContext;
    }
}
